package com.yjy.controller;

import cn.hutool.http.HttpUtil;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;

@RestController
public class TestController {

    @Autowired
    private RedissonClient redissonClient;

    public static volatile int num = 100;

    // 测试可重入锁
    @ResponseBody
    @GetMapping("/testRLock")
    public String order() throws InterruptedException {
        RLock lock = redissonClient.getLock("test:redissonLock");
        /*
            lock.lock(); // 最常见的使用方法
            lock.lock(10, TimeUnit.SECONDS); // 支持过期解锁功能，10s后自动解锁，无需调用unlock方法手动解锁
            lick.tryLock(3, 10, TimeUnit.SECONDS); // 尝试加锁，3秒内获取不到锁则直接返回false，加锁10s后自动解锁
         */
        if (lock.tryLock(10, 60, TimeUnit.SECONDS)) {
            try {
                // 步骤2：处理逻辑。。。
                if (num >= 0) {
                    System.out.println("order: " + num);
                    String res = "" + num;
                    num--;
                    Thread.sleep(1000);
                    return res;
                }
            } finally {
                // 步骤3：解锁
                lock.unlock();
            }
        }
        return "null";
    }

    // 压测，100条线程
    public static void main(String[] args) throws InterruptedException {
        CountDownLatch latch = new CountDownLatch(1000);
        for (int i = 0; i < 1000; i++) {
            new Thread(() -> {
                String result = HttpUtil.get("localhost:8080/testRLock");
                System.out.println(result);
                latch.countDown();
            }).start();
        }

        latch.await();
        System.out.println("全部线程执行结束");
    }
}